package com.ty.service;

import cn.hutool.core.date.DateUtil;
import cn.smart.core.util.UserContext;
import com.ty.dao.OutItemDao;
import com.ty.dao.PoMasterDao;
import com.ty.entity.OutItem;
import com.ty.entity.OutMasterQuery;
import com.ty.enums.PoStatus;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ty.entity.OutMaster;
import com.ty.dao.OutMasterDao;
import com.ty.service.OutMasterService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 销售出库批次明细表;(212_out_master)表服务实现类
 * @author : heimi
 * @date : 2025-6-10
 */
@Service
public class OutMasterService{
     
    @Autowired
    private OutMasterDao outMasterDao;
    @Autowired
    private OutItemDao outItemDao;

    @Autowired
    private PoMasterDao poMasterDao;

    public List<OutMaster> select(OutMasterQuery query) {
        return outMasterDao.select(query);
    }
    
    public Integer insert(OutMaster outMaster) {
        String outId = "OUT"+ DateUtil.format(DateUtil.date(),"yyyyMMddHHmmsssSSS");
        outMaster.setOutId(outId);
        List<OutItem> outItems = outMaster.getOutItems();
        for (OutItem item :outItems ){
            item.setOutId(outId);
            item.setLastUpdateBy(UserContext.get().getNickName());
            item.setExpiryDate(item.getExpiryDate().plusDays(item.getShelfLife()));
        }

        OutMasterService aop = (OutMasterService) (AopContext.currentProxy());
        aop.save(outMaster);
        return 1;
    }

    @Transactional
    public void save(OutMaster outMaster) {
        outMasterDao.insert(outMaster);
        outItemDao.insertBatch(outMaster.getOutItems());
        poMasterDao.updateStatus(outMaster.getOutId(), PoStatus.FINISHOUT.getCode());
    }

    public Integer update(OutMaster outMaster) {
        return outMasterDao.update(outMaster);
    }
    
    public Integer delete(Integer id) {
        return outMasterDao.delete(id);
    }
    
}